package fr.dsax.nounet.belote.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import fr.dsax.nounet.belote.jpa.GenericEntity;

@Repository
@Transactional
public abstract class GenericDaoImpl<T extends GenericEntity> implements IGenericDao<T> {

	@PersistenceContext
	protected EntityManager em;

	private Class<T> type;
	
	public GenericDaoImpl(Class<T> type) {
		this.type = type;
	}

	@Transactional
	public void create(T newInstance) {
		em.persist(newInstance);
		em.flush();
	}

	
	public T findById(Integer id) {
		return em.find(type, id);
	}

	public List<T> findAll() {
		CriteriaQuery<T> criteria = getCriteriaQuery();
		return em.createQuery(criteria).getResultList();
	}

	@Transactional
	public void update(T transientObject) {
		em.merge(transientObject);
	}

	@Transactional
	public void delete(T persistentObject) {
		em.remove(persistentObject);
	}

	public CriteriaQuery<T> getCriteriaQuery() {
		return em.getCriteriaBuilder().createQuery(type);
	}
	
	public CriteriaBuilder getCriteriaBuilder() {
		return em.getCriteriaBuilder();
	}

	@Override
	public Class<T> getEntityClass() {	
		return type;
	}
	
	
	
}
